package com.njupt.common;

import com.njupt.exception.ParamException;
import com.njupt.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class SpringExceptionResolver implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest request,
                                         javax.servlet.http.HttpServletResponse response,
                                         Object handler, Exception e) {
        String url = request.getRequestURI().toString();
        ModelAndView mv;
        String defaultMsg = "system error";

        //.json
        if(url.endsWith(".json")){
            if(e instanceof PermissionException || e instanceof ParamException){
                //是自定义的异常
                JsonData result = JsonData.fail(e.getMessage());
                mv = new ModelAndView("jsonView",result.toMap());//jsonView与spring-servlet中呼应
            }else {
                log.error("unkonen exception,url:"+url,e);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView",result.toMap());
            }
        }else if(url.endsWith(".page")){//.page
            log.error("unkonen exception,url:"+url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception",result.toMap());//去jsp目录下找一个叫exception的页面
        }else {
            log.error("unkonen exception,url:"+url,e);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}
